//
//  GNRCommonPicker.m
//  GNRPickCard_Example
//
//  Created by LvYuan on 2017/10/31.
//  Copyright © 2017年 ly918@qq.com. All rights reserved.
//

#import "GNRCommonPicker.h"
#import "GNRCommonPickCardConfig.h"
#import "GNRPickCardNavigationBar.h"
#import "GNRPickCardActionView.h"


typedef NS_ENUM(NSInteger, GNRCommonPickerFeatureType) {
    GNRCommonPickerFeatureTypeBaojia=1,//保价服务
    GNRCommonPickerFeatureTypeTransport,//配送工具服务
    GNRCommonPickerFeatureTypeGoodsWeight,//物品重量
    GNRCommonPickerFeatureTypeTextInput,//输入框（代收货款）
};

@interface GNRCommonPicker ()
{
    CGFloat keyboardHeight;
}
@property (nonatomic, assign)GNRCommonPickerFeatureType featrueType;

@property (nonatomic, strong)GNRCommonPickCardConfig *navigationConfig;
@property (nonatomic, strong)GNRCommonPickCardConfig *contentConfig;
@property (nonatomic, strong)GNRCommonPickCardConfig *actionConfig;

@property (nonatomic, strong)GNRPickCardNavigationBar *baseNavigationBar;
@property (nonatomic, strong)GNRPickCardActionView *actionView;

+ (id)pickerWithFeatrueType:(GNRCommonPickerFeatureType)featrueType;

@end

@implementation GNRCommonPicker
NSString * GNR_Observer_Key_Title = @"showTitle";

//MARK: - Getter
- (id<GNRPickCardBaseViewProtocol>)navBarConfiger{
    if (!_navigationConfig) {
        _navigationConfig = [[GNRCommonPickCardConfig alloc]init];
        _navigationConfig.contentNibName = @"GNRPickCardNavigationBar";
        _navigationConfig.contentHeight = 54.0;
    }
    return _navigationConfig;
}

- (id<GNRPickCardBaseViewProtocol>)contentConfiger{
    if (!_contentConfig) {
        _contentConfig = [[GNRCommonPickCardConfig alloc]init];
        _contentConfig.contentHeight = 254.0;
        if (_contentView) {
            _contentConfig.contentView = _contentView;
        }
    }
    return _contentConfig;
}

- (id<GNRPickCardBaseViewProtocol>)actionConfiger{
    if (!_actionConfig) {
        _actionConfig = [[GNRCommonPickCardConfig alloc]init];
        _actionConfig.contentNibName = @"GNRPickCardActionView";
        _actionConfig.contentHeight = 60.0;
    }
    return _actionConfig;
}

- (GNRPickCardNavigationBar *)baseNavigationBar{
    if (!_baseNavigationBar) {
        _baseNavigationBar = (GNRPickCardNavigationBar *)self.navBarConfiger.contentView;
    }
    return _baseNavigationBar;
}

- (GNRPickCardActionView *)actionView{
    if (!_actionView) {
        _actionView = (GNRPickCardActionView *)self.actionConfiger.contentView;
    }
    return _actionView;
}

- (instancetype)init{
    if (self = [super init]) {
        
    }
    return self;
}

- (GNRCommonPicker *)initWithContentView:(UIView *)contentView{
    if (self = [super init]) {
        self.contentView = contentView;
    }
    return self;
}

- (GNRCommonPicker *)initWithFeatrueType:(GNRCommonPickerFeatureType)featrueType{
    if (self = [super init]) {
        self.featrueType = featrueType;
        self.contentView = [self contentViewWithFeatrueType:featrueType];
    }
    return self;
}

+ (GNRCommonPicker *)pickerWithContentView:(UIView *)contentView{
    GNRCommonPicker *picker = [[GNRCommonPicker alloc]initWithContentView:contentView];
    return picker;
}

+ (GNRCommonPicker *)pickerWithFeatrueType:(GNRCommonPickerFeatureType)featrueType{
    GNRCommonPicker *picker = [[GNRCommonPicker alloc]initWithFeatrueType:featrueType];
    return picker;
}

//MAKR: - 保价
+ (GNRCommonPicker *)pickerForBaojiaWithItems:(NSMutableArray <id<GNRSelectionItemProtocol>>*)items
                              selectItemBlock:(GNRCommonPickerSelectItemBlock)selectItemBlock
                                  actionBlock:(GNRCommonPickerActionBlock)actionBlock
                           footerPressedBlock:(void (^)(GNRBaojiaFooterView *baojiaFooter,GNRPickCard *pickCard))footerPressedBlock{
    GNRCommonPicker *picker = [GNRCommonPicker pickerWithFeatrueType:GNRCommonPickerFeatureTypeBaojia];
    GNRSelectionCardView *cardView = (GNRSelectionCardView *)picker.contentView;
    GNRPickCardActionView *actionView = picker.actionView;
    cardView.config_UI = [picker contentConfigWithFeatrueType:GNRCommonPickerFeatureTypeBaojia];
    cardView.items = [NSMutableArray arrayWithArray:items];
    __weak typeof(picker) weakPicker = picker;
    __block id<GNRSelectionItemProtocol>selectionItem = nil;
    cardView.selectBlock = ^(id<GNRSelectionItemProtocol>item) {
        selectionItem = item;
        if (selectItemBlock) {
            selectItemBlock(item,weakPicker);
        }
        actionView.confirmBtn.enabled = YES;
    };
    cardView.selectFooterBlock = ^(UIView *footerView) {
        if (footerPressedBlock) {
            footerPressedBlock((GNRBaojiaFooterView*)footerView,weakPicker);
        }
    };
    actionView.confirmBlock = ^(UIButton *confirmBtn) {
        if (actionBlock) {
            actionBlock(selectionItem,weakPicker);
        }
    };
    return picker;
}

//配送工具
+ (GNRCommonPicker *)pickerForTransportWithItems:(NSMutableArray <id<GNRSelectionItemProtocol>>*)items
                                selectItemBlock:(GNRCommonPickerSelectItemBlock)selectItemBlock
                                    actionBlock:(GNRCommonPickerActionBlock)actionBlock{
    GNRCommonPicker *picker = [GNRCommonPicker pickerWithFeatrueType:GNRCommonPickerFeatureTypeTransport];
    GNRSelectionCardView *cardView = (GNRSelectionCardView *)picker.contentView;
    GNRPickCardActionView *actionView = picker.actionView;
    cardView.config_UI = [picker contentConfigWithFeatrueType:GNRCommonPickerFeatureTypeTransport];
    cardView.items = [NSMutableArray arrayWithArray:items];
    __weak typeof(picker) weakPicker = picker;
    __block id<GNRSelectionItemProtocol>selectionItem = nil;
    cardView.selectBlock = ^(id<GNRSelectionItemProtocol>item) {
        selectionItem = item;
        if (selectItemBlock) {
            selectItemBlock(item,weakPicker);
        }
        actionView.confirmBtn.enabled = YES;
    };
    actionView.confirmBlock = ^(UIButton *confirmBtn) {
        if (actionBlock) {
            actionBlock(selectionItem,weakPicker);
        }
    };
    return picker;
}

//物品重量
+ (GNRCommonPicker *)pickerForGoodsWeightWithItems:(NSMutableArray <id<GNRSelectionItemProtocol>>*)items
                                   selectItemBlock:(GNRCommonPickerSelectItemBlock)selectItemBlock
                                       actionBlock:(GNRCommonPickerActionBlock)actionBlock{
    GNRCommonPicker *picker = [GNRCommonPicker pickerWithFeatrueType:GNRCommonPickerFeatureTypeGoodsWeight];
    GNRSelectionCardView *cardView = (GNRSelectionCardView *)picker.contentView;
    GNRPickCardActionView *actionView = picker.actionView;
    cardView.config_UI = [picker contentConfigWithFeatrueType:GNRCommonPickerFeatureTypeGoodsWeight];
    cardView.items = [NSMutableArray arrayWithArray:items];
    __weak typeof(picker) weakPicker = picker;
    __block id<GNRSelectionItemProtocol>selectionItem = nil;
    cardView.selectBlock = ^(id<GNRSelectionItemProtocol>item) {
        selectionItem = item;
        if (selectItemBlock) {
            selectItemBlock(item,weakPicker);
        }
        actionView.confirmBtn.enabled = YES;
    };
    actionView.confirmBlock = ^(UIButton *confirmBtn) {
        if (actionBlock) {
            actionBlock(selectionItem,weakPicker);
        }
    };
    return picker;
}

//文本输入
+ (GNRCommonPicker *)pickerForInputConfig:(id<GNRTextInputProtocol>)inputConfig
                              actionBlock:(GNRCommonPickerActionBlock)actionBlock{
    GNRCommonPicker *picker = [GNRCommonPicker pickerWithFeatrueType:GNRCommonPickerFeatureTypeTextInput];
    GNRInputCardView *cardView = (GNRInputCardView *)picker.contentView;
    cardView.inputConfig = inputConfig?:[picker contentConfigWithFeatrueType:GNRCommonPickerFeatureTypeTextInput];

    GNRPickCardActionView *actionView = picker.actionView;
    actionView.confirmBtn.enabled = YES;
    __weak typeof(picker) weakPicker = picker;
    actionView.confirmBlock = ^(UIButton *confirmBtn) {
        if (actionBlock) {
            actionBlock(cardView.textField.text,weakPicker);
        }
    };
    return picker;
}

- (UIView *)contentViewWithFeatrueType:(GNRCommonPickerFeatureType)featrueType{
    UIView *view = nil;
    NSString *nibName = [GNRCommonPicker contentViewNibNameWithFeatrueType:featrueType];
    if (nibName) {
        view = [[[NSBundle mainBundle]loadNibNamed:nibName owner:nil options:nil] firstObject];
    } else {
        NSAssert(nibName, @"请添加此类型的内容视图的NibName!");
    }
    return view;
}

- (id)contentConfigWithFeatrueType:(GNRCommonPickerFeatureType)featrueType{
    NSString *configClassName = [GNRCommonPicker contentConfigClassNameWithFeatrueType:featrueType];
    id config = nil;
    if (configClassName) {
        config = [NSClassFromString(configClassName) new];
    } else {
        NSAssert(configClassName, @"请添加此类型的内容视图的配置项!");
    }
    return config;
}

+ (NSString *)contentViewNibNameWithFeatrueType:(GNRCommonPickerFeatureType)featrueType{
    switch (featrueType) {
        case GNRCommonPickerFeatureTypeBaojia:
        case GNRCommonPickerFeatureTypeTransport:
        case GNRCommonPickerFeatureTypeGoodsWeight:
        {
            return @"GNRSelectionCardView";
        }
            break;
        case GNRCommonPickerFeatureTypeTextInput:return @"GNRInputCardView";
        default:
            break;
    }
    return nil;
}

+ (NSString *)contentConfigClassNameWithFeatrueType:(GNRCommonPickerFeatureType)featrueType{
    switch (featrueType) {
        case GNRCommonPickerFeatureTypeBaojia:return @"GNRBaojiaCardConfig";
        case GNRCommonPickerFeatureTypeTransport:return @"GNRTransportCardConfig";
        case GNRCommonPickerFeatureTypeGoodsWeight:return @"GNRGoodsWeightCardConfig";
        case GNRCommonPickerFeatureTypeTextInput:return @"GNRInputBaseConfig";
        default:
            break;
    }
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self updateNavigation];
    
    [self.baseNavigationBar.closeBtn addTarget:self action:@selector(closeBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addObserver:self forKeyPath:GNR_Observer_Key_Title options:NSKeyValueObservingOptionNew context:nil];
    
    [self registerNotifications];
    // Do any additional setup after loading the view.
}

- (void)registerNotifications{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWasShown_gnr:)
                               name:UIKeyboardWillShowNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWasShown_gnr:)
                               name:UIKeyboardDidShowNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillBeHidden_gnr:)
                               name:UIKeyboardWillHideNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillBeHidden_gnr:)
                               name:UIKeyboardDidHideNotification
                             object:nil];
}

- (void)keyboardWasShown_gnr:(NSNotification *)notify{
    NSDictionary* info = [notify userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    keyboardHeight = kbSize.height;
    [self showKeyboardAnimation:YES];
}

- (void)keyboardWillBeHidden_gnr:(NSNotification *)notify{
    [self hideKeyboardAnimation:YES];
}

- (void)showKeyboardAnimation:(BOOL)animation{
    GNRWEAK_SELF;
    //super content
    CGFloat superHeight_Tmp = 238.f;
    CGFloat contentHeight_Tmp = superHeight_Tmp - navigationBarHeight - actionViewHeight;
    [UIView animateWithDuration:0.2 animations:^{
        [wself.superView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(wself.view.mas_bottom).offset(-keyboardHeight);
            make.height.mas_equalTo(superHeight_Tmp);
        }];
        [wself.contentSuperView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(contentHeight_Tmp);
        }];
        [wself.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hideKeyboardAnimation:(BOOL)animation{
    GNRWEAK_SELF;
    //super content
    [UIView animateWithDuration:0.2 animations:^{
        [wself.superView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(wself.view.mas_bottom).offset(0);
            make.height.mas_equalTo(superViewTotalHeight);
        }];
        [wself.contentSuperView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(contentViewHeight);
        }];
        [wself.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:GNR_Observer_Key_Title] && object == self) {
        [self updateNavigation];
    }
}

- (void)updateNavigation{
    self.baseNavigationBar.title = self.showTitle;
}

- (void)closeBtnPressed:(id)sender{
    //delegate
    if ([self.delegate respondsToSelector:@selector(closePressedPickCard:)]) {
        [self.delegate closePressedPickCard:self];
    }
    //block
    if (self.closePressBlock) {
        self.closePressBlock(self);
    }
}

- (void)removeNotifications{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [notificationCenter removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [notificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [notificationCenter removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

- (void)dealloc{
    [self removeObserver:self forKeyPath:GNR_Observer_Key_Title];
    [self removeNotifications];
    GNRAlertLog(@"");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
